package com.zzg.srb.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzg.srb.common.Enum.IsTrueEnum;
import com.zzg.srb.core.entity.pojo.Borrower;
import com.zzg.srb.core.entity.pojo.BorrowerAttach;
import com.zzg.srb.core.entity.pojo.UserInfo;
import com.zzg.srb.core.entity.pojo.UserIntegral;
import com.zzg.srb.core.entity.vo.BorrowerApprovalVo;
import com.zzg.srb.core.entity.vo.BorrowerAttachVo;
import com.zzg.srb.core.entity.vo.BorrowerDetailVo;
import com.zzg.srb.core.entity.vo.BorrowerVo;
import com.zzg.srb.core.enums.BorrowerStatusEnum;
import com.zzg.srb.core.enums.DictEnum;
import com.zzg.srb.common.Enum.SexEnum;
import com.zzg.srb.core.enums.IntegralEnum;
import com.zzg.srb.core.mapper.BorrowerAttachMapper;
import com.zzg.srb.core.mapper.BorrowerMapper;
import com.zzg.srb.core.mapper.UserInfoMapper;
import com.zzg.srb.core.mapper.UserIntegralMapper;
import com.zzg.srb.core.service.BorrowerAttachService;
import com.zzg.srb.core.service.BorrowerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzg.srb.core.service.DictService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 借款人 服务实现类
 * </p>
 *
 * @author zhengzg
 * @since 2022-05-27
 */
@Service
public class BorrowerServiceImpl extends ServiceImpl<BorrowerMapper, Borrower> implements BorrowerService {

    @Resource
    private BorrowerAttachMapper borrowerAttachMapper;

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private DictService dictService;

    @Resource
    private BorrowerAttachService borrowerAttachService;

    @Resource
    private UserIntegralMapper userIntegralMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveBorrowerVoByUserId(BorrowerVo borrowerVo, Long userId) {

        UserInfo userInfo = userInfoMapper.selectById(userId);

        //保存借款人信息
        Borrower borrower = new Borrower();
        BeanUtils.copyProperties(borrowerVo,borrower);
        borrower.setUserId(userInfo.getId());
        borrower.setName(userInfo.getName());
        borrower.setIdCard(userInfo.getIdCard());
        borrower.setMobile(userInfo.getMobile());
        borrower.setIsMarry(borrowerVo.getMarry());
        //设置状态为认证中
        borrower.setStatus(BorrowerStatusEnum.AUTH_RUN.getStatus());
        baseMapper.insert(borrower);

        //保存附件
        List<BorrowerAttach> borrowerAttachList = borrowerVo.getBorrowerAttachList();
        borrowerAttachList.forEach(borrowerAttach -> {
            borrowerAttach.setBorrowerId(borrower.getId());
            borrowerAttachMapper.insert(borrowerAttach);
        });

        //更新会员状态，更新为认证中
        userInfo.setBorrowAuthStatus(BorrowerStatusEnum.AUTH_RUN.getStatus());
        userInfoMapper.updateById(userInfo);
    }

    @Override
    public Integer getStatusByUserId(Long userId) {
        LambdaQueryWrapper<Borrower> borrowerQueryWrapper = new LambdaQueryWrapper<>();
        borrowerQueryWrapper
                .select(Borrower::getStatus)
                .eq(Borrower::getUserId,userId);
        List<Object> objects = baseMapper.selectObjs(borrowerQueryWrapper);

        if (CollectionUtils.isEmpty(objects)){
            //借款人尚未提交信息
            return BorrowerStatusEnum.NO_AUTH.getStatus();
        }

        return (Integer) objects.get(0);
    }

    @Override
    public IPage<Borrower> listPage(Page<Borrower> pageParam, String keyword) {
        LambdaQueryWrapper<Borrower> borrowQueryWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.isEmpty(keyword)){
            return baseMapper.selectPage(pageParam,null) ;
        }

        borrowQueryWrapper
                .like(Borrower::getName,keyword)
                .or()
                .like(Borrower::getIdCard,keyword)
                .or()
                .like(Borrower::getMobile,keyword)
                .orderByDesc(Borrower::getId);

        return baseMapper.selectPage(pageParam, borrowQueryWrapper);
    }

    @Override
    public BorrowerDetailVo getBorrowerDetailVoById(Long id) {

        //获取借款人信息
        Borrower borrower = baseMapper.selectById(id);

        //填充基本借款人信息
        BorrowerDetailVo borrowerDetailVo = new BorrowerDetailVo();
        BeanUtils.copyProperties(borrower,borrowerDetailVo);

        //婚否
        borrowerDetailVo.setMarry(IsTrueEnum.getEnumNameByValue(borrower.getIsMarry()));
        //性别
        borrowerDetailVo.setSex(SexEnum.getSexNameByValue(borrower.getSex()));

        //计算下拉列表选中的内容
        String education = dictService.getNameByParentDictCodeAndValue(DictEnum.EDUCATION.getDictCode(),borrower.getEducation());
        String industry = dictService.getNameByParentDictCodeAndValue(DictEnum.INDUSTRY.getDictCode(), borrower.getIndustry());
        String income = dictService.getNameByParentDictCodeAndValue(DictEnum.INCOME.getDictCode(), borrower.getIncome());
        String returnSource = dictService.getNameByParentDictCodeAndValue(DictEnum.RETURN_SOURCE.getDictCode(), borrower.getReturnSource());
        String contactRelation = dictService.getNameByParentDictCodeAndValue(DictEnum.RELATION.getDictCode(), borrower.getContactsRelation());

        //设置下拉列表选中的内容
        borrowerDetailVo.setEducation(education);
        borrowerDetailVo.setIndustry(industry);
        borrowerDetailVo.setIncome(income);
        borrowerDetailVo.setReturnSource(returnSource);
        borrowerDetailVo.setContactsRelation(contactRelation);

        //审批状态
        String status = BorrowerStatusEnum.getMsgByStatus(borrower.getStatus());
        borrowerDetailVo.setStatus(status);

        //获取附件Vo列表
        List<BorrowerAttachVo> borrowerAttachVoList = borrowerAttachService.selectBorrowerAttachVoList(id);
        borrowerDetailVo.setBorrowerAttachVOList(borrowerAttachVoList);

        return borrowerDetailVo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void approval(BorrowerApprovalVo borrowerApprovalVo) {

        //借款人认证状态
        Long borrowerId = borrowerApprovalVo.getBorrowerId();
        Borrower borrower = baseMapper.selectById(borrowerId);
        borrower.setStatus(borrowerApprovalVo.getStatus());
        baseMapper.updateById(borrower);

        Long userId = borrower.getUserId();
        UserInfo userInfo = userInfoMapper.selectById(userId);

        //添加积分
        UserIntegral userIntegral = new UserIntegral();
        userIntegral.setUserId(userId);
        userIntegral.setIntegral(borrowerApprovalVo.getInfoIntegral());
        userIntegral.setContent(IntegralEnum.BORROWER_INFO.getMsg());
        userIntegralMapper.insert(userIntegral);

        int curInteger = borrowerApprovalVo.getInfoIntegral() + userInfo.getIntegral();
        if (borrowerApprovalVo.getIsIdCardOk()){
            curInteger += IntegralEnum.BORROWER_IDCARD.getIntegral();
            userIntegral = new UserIntegral();
            userIntegral.setId(userId);
            userIntegral.setIntegral(IntegralEnum.BORROWER_IDCARD.getIntegral());
            userIntegral.setContent(IntegralEnum.BORROWER_IDCARD.getMsg());
            userIntegralMapper.insert(userIntegral);
        }

        if (borrowerApprovalVo.getIsHouseOk()){
            curInteger += IntegralEnum.BORROWER_HOUSE.getIntegral();
            userIntegral = new UserIntegral();
            userIntegral.setId(userId);
            userIntegral.setIntegral(IntegralEnum.BORROWER_HOUSE.getIntegral());
            userIntegral.setContent(IntegralEnum.BORROWER_HOUSE.getMsg());
            userIntegralMapper.insert(userIntegral);
        }

        if (borrowerApprovalVo.getIsCarOk()){
            curInteger += IntegralEnum.BORROWER_CAR.getIntegral();
            userIntegral = new UserIntegral();
            userIntegral.setId(userId);
            userIntegral.setIntegral(IntegralEnum.BORROWER_CAR.getIntegral());
            userIntegral.setContent(IntegralEnum.BORROWER_CAR.getMsg());
            userIntegralMapper.insert(userIntegral);
        }

        userInfo.setIntegral(curInteger);

        //修改审核状态
        userInfo.setBorrowAuthStatus(borrowerApprovalVo.getStatus());
        userInfoMapper.updateById(userInfo);
    }
}
